<?php

namespace App\Jobs\Controller;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalDynamicConst;
use App\Consts\GlobalNoteConst;
use App\Jobs\BaseJob;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\IndexDynamic;
use App\Models\SysArticle;
use App\Models\UserAttention;
use App\Models\UserRecommend;

class DynamicJob extends BaseJob
{

    /**
     * @param $msgContent
     * @return bool
     */
    public function create($msgContent)
    {
        // 业务加锁，防止重复执行（注意执行完后要释放锁）
        $lock = Cache::getInstance([
            'target_id' => $msgContent['msgContent']['target_id'] ?? 0,
            'user_id' => $msgContent['msgContent']['user_id'] ?? 0,
        ])->setnx(CacheKey::LOCK_DYNAMIC_CREATE, 1);
        if (!$lock) {
            return false;
        }

        // 新增动态
        $dynamicRepository = repository()->DynamicRepository;
        $dynamic = $dynamicRepository->addDynamic(ArrayHelper::merge($msgContent['msgContent'], [
            'dynamic_id' => IdBuilder::getUniqueID(),
        ]));
        if (!$dynamic) {
            return false;
        }

        // 新增动态[feed_dynamic]表记录
        $feedDynamicRepository = repository()->FeedDynamicRepository;
        $feedDynamicRepository->create([
            'user_id' => $dynamic->user_id,
            'dynamic_id' => $dynamic->dynamic_id,
            'apply_at' => time(),
            'dynamic_type' => $dynamic->type,
        ]);

        // 队列添加动态日志
        $logData = [
            'send_user_id' => $dynamic->user_id,
            'receive_user_id' => $dynamic->user_id,
            'action_id' => $dynamic->dynamic_id,
            'action_type' => GlobalCounterConst::ACTION_TYPE_DYNAMIC,
            'target_id' => $dynamic->target_id,
            'target_type' => $dynamic->target_type,
            'created_at' => time(),
        ];
        service()->LogCountService->createLogByQueue($logData);

        // 给所有粉丝push关注动态
        $relationshipRepository = repository()->RelationshipRepository;
        $followerIdArr = $relationshipRepository->getUserAllFollowersIdArr($dynamic->user_id);
        $followerIdArr = collect(ArrayHelper::merge(ArrayHelper::toArray($followerIdArr), [$dynamic->user_id]))->unique()->toArray();
        foreach ($followerIdArr as $followerId) {
            // 新增[user_attention_]表记录
            $model = UserAttention::getModel($followerId)
                ->where('user_attention_id', $followerId)
                ->where('user_id', $dynamic->user_id)
                ->where('target_id', $dynamic->dynamic_id)
                ->first();
            if (!$model) {
                UserAttention::getModel($followerId)->create([
                    'user_attention_id' => $followerId,
                    'user_id' => $dynamic->user_id,
                    'target_id' => $dynamic->dynamic_id,
                    'target_type' => GlobalConst::TARGET_TYPE_DYNAMIC,
                    'is_view' => GlobalDynamicConst::IS_VIEW,
                    'is_deleted' => GlobalConst::IS_NOT_DELETE,
                    'apply_at' => $dynamic->created_at,
                    'updated_at' => $dynamic->updated_at,
                    'dynamic_type' => $dynamic->type,
                ]);
            } else {
                $model->updateFormat([
                    'is_view' => GlobalDynamicConst::IS_VIEW,
                    'is_deleted' => GlobalConst::IS_NOT_DELETE,
                ]);
            }
        }

        // 业务执行完毕，释放锁
        Cache::getInstance([
            'target_id' => $msgContent['msgContent']['target_id'] ?? 0,
            'user_id' => $msgContent['msgContent']['user_id'] ?? 0,
        ])->delete(CacheKey::LOCK_DYNAMIC_CREATE);

        return true;
    }

    public function deleteByDynamic($msgContent)
    {
        $data = $msgContent['msgContent'];

        // 动态的主体主体是文章
        if ($data['target_type'] == GlobalConst::TARGET_TYPE_ARTICLE) {
            $article = SysArticle::getModel($data['target_id'])
                ->where('article_id', $data['target_id'])
                ->first();
            if (!$article) {
                return false;
            }

            // 删除文章动态和关注推送
            return $this->deleteByArticle([
                'msgContent' => [
                    'dynamic_id' => $msgContent['msgContent']['dynamic_id'],
                    'user_id' => $article->author_id,
                    'article_id' => $article->article_id,
                ]
            ]);
        }

        // 动态的主体是笔记
        if ($data['target_type'] == GlobalConst::TARGET_TYPE_NOTE) {
            $noteRepository = repository()->NoteRepository;
            // 删除笔记
            $note = $noteRepository->delNoteById($data['target_id']);
            if (!$note) {
                return false;
            }

            // 同步更新缓存计数
            $noteIsPublic = $note->is_public == GlobalNoteConst::IS_PUBLIC;

            $counterKey = $noteIsPublic ? GlobalCounterConst::COUNT_PUBLIC_NOTE : GlobalCounterConst::COUNT_SELF_NOTE;

            Cache::getInstance([
                'user_id' => $note->user_id
            ])->incrFromArray(CacheKey::COUNTER_USER, $counterKey, GlobalCounterConst::DECREASE);

            Cache::getInstance([
                'article_id' => $note->article_id
            ])->incrFromArray(CacheKey::COUNTER_ARTICLE, $counterKey, GlobalCounterConst::DECREASE);

            Cache::getInstance([
                'user_id' => $note->user_id,
                'article_id' => $note->article_id,
            ])->incrFromArray(CacheKey::COUNTER_USER_ARTICLE, $counterKey, GlobalCounterConst::DECREASE);

            // 队列添加删除笔记日志
            $noteIsPublic = $note->is_public == GlobalNoteConst::IS_PUBLIC;

            $actionType = $noteIsPublic ? GlobalCounterConst::ACTION_TYPE_DEL_PUBLIC_NOTE : GlobalCounterConst::ACTION_TYPE_DEL_SELF_NOTE;

            $logData = [
                'send_user_id' => $note->user_id,
                'receive_user_id' => $note->user_id,
                'action_id' => $note->note_id,
                'action_type' => $actionType,
                'target_id' => $note->article_id,
                'target_type' => GlobalConst::TARGET_TYPE_ARTICLE,
                'created_at' => time(),
            ];
            service()->LogCountService->createLogByQueue($logData);

            // 删除笔记动态和关注推送
            $this->deleteByNote([
                'msgContent' => [
                    'user_id' => $note->user_id,
                    'target_id' => $note->note_id,
                    'is_public' => $note->is_public,
                    'dynamic_id' => $msgContent['msgContent']['dynamic_id'],
                ]
            ]);

            // 除笔记相关评论消息
            repository()->CommentRepository->deleteByNote($note->note_id, $note->user_id);
        }

        return true;
    }

    public function deleteByArticle($msgContent)
    {
        // 更新用户计数缓存
        Cache::getInstance([
            'user_id' => $msgContent['msgContent']['user_id'],
        ])->incrFromArray(
            CacheKey::COUNTER_USER,
            GlobalCounterConst::COUNT_DYNAMIC,
            GlobalCounterConst::DECREASE
        );

        Cache::getInstance([
            'article_id' => $msgContent['msgContent']['target_id'],
        ])->incrFromArray(
            CacheKey::COUNTER_ARTICLE,
            GlobalCounterConst::COUNT_USER_RECOMMEND,
            GlobalCounterConst::DECREASE
        );

        UserRecommend::getModel($msgContent['msgContent']['user_id'])
            ->where('user_id', $msgContent['msgContent']['user_id'])
            ->where('target_id', $msgContent['msgContent']['target_id'])
            ->update(['is_deleted' => GlobalConst::IS_DELETED]);

        $dynamic = null;
        $indexDynamic = IndexDynamic::getModel()
            ->where('target_id', $msgContent['msgContent']['target_id'])
            ->where('user_id', $msgContent['msgContent']['user_id'])
            ->where('type', $msgContent['msgContent']['dynamic_type'])
            ->first();
        if (!$indexDynamic) {
            return false;
        }

        $dynamic = repository()->DynamicRepository->getDynamicById($indexDynamic->dynamic_id);
        if (!$dynamic) {
            return false;
        }

        $indexDynamic->update(['is_deleted' => GlobalConst::IS_DELETED]);

        $dynamic->update(['is_deleted' => GlobalConst::IS_DELETED]);

        if ($dynamic) {
            // 删除[feed_dynamic]记录
            repository()->FeedDynamicRepository->deleteByCondition(['dynamic_id' => $dynamic->dynamic_id]);

            // 删除该用户所有粉丝的[user_attention_]记录
            repository()->UserRepository->deleteByUserAttentionIdAndTargetId($msgContent['msgContent']['user_id'], $dynamic->dynamic_id);

            // 队列添加删除动态日志
            $logData = [
                'send_user_id' => $msgContent['msgContent']['user_id'],
                'receive_user_id' => $dynamic->user_id,
                'action_id' => $dynamic->dynamic_id,
                'action_type' => GlobalCounterConst::ACTION_TYPE_DEL_DYNAMIC,
                'target_id' => $dynamic->target_id,
                'target_type' => $dynamic->target_type,
                'created_at' => time(),
            ];
            service()->LogCountService->createLogByQueue($logData);
        }

        return true;
    }

    public function deleteByNote($msgContent)
    {
        /**
         * [
         *      [msgContent] => ["user_id":"用户ID","target_id":"动态主体ID","is_public":0]
         * ]
         */
        $dynamicRepository = repository()->DynamicRepository;
        $dynamic = $dynamicRepository->delDynamicByTargetId($msgContent['msgContent']['target_id']);

        if ($msgContent['msgContent']['is_public'] == GlobalNoteConst::IS_PUBLIC) {
            // 更新用户计数缓存
            Cache::getInstance(['user_id' => $msgContent['msgContent']['user_id']])
                ->incrFromArray(
                    CacheKey::COUNTER_USER,
                    GlobalCounterConst::COUNT_DYNAMIC,
                    GlobalCounterConst::DECREASE
                );

            if ($dynamic) {
                // 队列添加删除动态日志
                $logData = [
                    'send_user_id' => $msgContent['msgContent']['user_id'],
                    'receive_user_id' => $dynamic->user_id,
                    'action_id' => $dynamic->dynamic_id,
                    'action_type' => GlobalCounterConst::ACTION_TYPE_DEL_DYNAMIC,
                    'target_id' => $dynamic->target_id,
                    'target_type' => $dynamic->target_type,
                    'created_at' => time(),
                ];
                service()->LogCountService->createLogByQueue($logData);
            }
        }

        if ($dynamic) {
            // 删除[feed_dynamic]记录
            repository()->FeedDynamicRepository->deleteByCondition(['dynamic_id' => $dynamic->dynamic_id]);
            // 删除该用户所有粉丝的[user_attention_]记录
            repository()->UserRepository->deleteByUserAttentionIdAndTargetId($msgContent['msgContent']['user_id'], $dynamic->dynamic_id);
        }

        return true;
    }

}
